import 'dart:async';

import 'package:flutter/material.dart';

class MyCountdown extends StatefulWidget {
  late final MyCountdownState _myCountdownState;


  MyCountdown(Key key, int defaultMinTime):super(key: key){
    _myCountdownState = MyCountdownState(defaultMinTime*60);
  }

  @override
  State<StatefulWidget> createState() {
    return _myCountdownState;
  }
}

class MyCountdownState extends State<MyCountdown>{
  int _defaultSecond = 0;
  int _second = 0;
  Timer? _timer;
  Function()? _finishCallback;


  MyCountdownState(this._second) {
    _defaultSecond = _second;
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      _formatTime(_second),
    );
  }

  void start() {
    if(_timer == null) {
      var period = Duration(seconds: 1);
      _timer = Timer.periodic(period, (timer) {
        // 每隔 1s 更新界面
        setState(() {
          _second--;
        });
        if(_second == 0) {
          cancel();
          _finishCallback?.call();
        }
      });
    }
  }



  void cancel() {
    _timer?.cancel();
    _timer = null;

    setState(() {
      _second = _defaultSecond;
    });
  }

  @override
  void dispose() {
    super.dispose();
    cancel();
  }

  void finishCallback(Function() callback) {
    _finishCallback = callback;
  }

  void setTime(int min) {
    setState(() {
      _second = min*60;
    });
  }

  String _formatTime(int second){
    var d = Duration(seconds: second);
    String minutes = d.inMinutes.toString().padLeft(2, "0");
    String seconds = d.inSeconds.remainder(60).toString().padLeft(2, "0");

    return "$minutes:$seconds";
  }

}